<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Usertree extends Model{

	private static $nodes=[];
	public static function separat_format(&$list){
		$uids = get_array_keys($list->items(),'uid');
		$users = DB::table('userdata')->whereIn('id',$uids)->get()->toArray();
		$users = arrays_set_key($users,'id');
		

		foreach ($list->items() as $item) {
			$item->user = $users[$item->uid];
		}
	}

	public static function nodes($uid){
		$data = DB::table('user_tree')->where('pid',$uid)->get()->toArray();
		foreach($data as $item){
			SELF::$nodes[] = $item;
			SELF::nodes($item->uid);
		}

		
		$list = SELF::$nodes;
		$uids = get_array_keys($list,'uid');
		$users = DB::table('userdata')->whereIn('id',$uids)->get()->toArray();
		$users = arrays_set_key($users,'id');
		foreach ($list as &$item) {
			$item->user = $users[$item->uid];
		}
		return $list;
	}

	public static function add($uid,$pid){
		if($pid == 0){
			$data = [
				'uid'=>$uid,
				'pid'=>$pid,
				'tree_id'=>$uid,
				'left'=>1,
				'right'=>2,
				'hight'=>0
			];
			return DB::table('user_tree')->insertGetId($data);
		}else{
			$father = DB::table('user_tree')->where('uid',$pid)->first();
			$data = [
				'uid'=>$uid,
				'pid'=>$pid,
				'tree_id'=>$father->tree_id,
				'left'=>$father->right,
				'right'=>$father->right+1,
				'hight'=>$father->hight+1,
			];
			DB::beginTransaction();
			#修改右节点
			$step1 = DB::table('user_tree')->where([
				['tree_id','=',$father->tree_id],
				['left','>',$father->left],
			])->update([
				'left'=>DB::raw("`left`+2"),
				'right'=>DB::raw("`right`+2")
			]);
			#修改父
			$step2 = DB::table('user_tree')->where([
				['tree_id','=',$father->tree_id],
				['left','<=',$father->left],
				['right','>=',$father->right],
			])->update([
				'right'=>DB::raw("`right`+2")
			]);
			#插表
			#$step3 = DB::table('user_tree')->insertGetId($data);
			$step3 = DB::table('user_tree')->where('uid',$uid)->update([
				'left'=>$father->right,
				'right'=>$father->right+1,
				'tree_id'=>$father->tree_id,
				'hight'=>$father->hight+1,
			]);
			if($step1!==false && $step2!==false && $step3!==false){
				DB::commit();
				return $step3;
			}else{
				DB::rollBack();
				return false;
			}
		}
	}
}